
#include "../includes.h"

#include "FPGAdata.h"
#include "FPGAdata_VME_M.h"

extern char FPGA_Data[];

int l=0;
void fpga_init(int fd)
{
int i,j,k=0;
unsigned char temp;
int size;
int oneof10=(int)(FPGADATASIZE/10);


	SetFPGAData();	//set as output
	SetFPGAClk();	//set as output
	SetFPGAProg();	//set as output
	SetFPGADone();	//set as input	
	
	SetFPGAmLatch();	//set as output
	SetFPGAmClear();	//set as output
	SetFPGAmClearLow();
	SetFPGAmLatchLow();

//	SetDACPort();		//set DAC port	,sewon
	
	SetFPGAProgHigh();
	
	msleep(20);
	
	SetFPGAProgLow();
	SetFPGAProgHigh();
	msleep(80);

	if( GetFPGADone() == 1 ){printf("FPGA Done Fail... !!\r\n");}
	else {printf("FPGA Done Ok... !!!\r\n");}
	
	msleep(100);
	if( l == 0 ){
		l = 1;
		CONFIG.FPGACH = 0;
	}
	if( CONFIG.FPGACH == 0 ){//sewon
		printf("fpgach==0\n");
		size = write( fd,(char *)FPGAData, FPGADATASIZE );
	}
	else if( CONFIG.FPGACH == 1 ){//sewon
		printf("fpgach==1\n");
		size = write( fd,(char *)FPGAData_VME_M, FPGADATASIZE_VME_M );
	}
	
	msleep(100);

	if( GetFPGADone() == 1 ){printf("FPGA Prog (%d) OK... !!!\r\n",size);}
	else {printf("FPGA Prog Error... !!!\r\n");}
	
	strcpy(FPGA_Version,FPGA_VERSION_STRING);
}


void ChangeDACValue(int fd, int volt)
{
    int i;
	
    if( OSC.kind == Rubidium_OSC ){ return; }	//sewon

    SetDacCsLow(fd); 
	
	if( volt > 65534 ) volt = 65534;
	else if( volt < 0 ) volt = 0 ;	
	
    for( i = 0; i < 16; i++){

        SetDacClkLow(fd); 
        
        if (((volt<<i)&0x8000)) {SetDacDinHigh(fd);}
        else {SetDacDinLow(fd);}
        	
        SetDacClkHigh(fd); 
    }

    SetDacCsHigh(fd); 
	ave_PushValue(&ave_dac, (double)volt);
}

void Print_Binary(unsigned char input)	//sewon
{
	unsigned char c = 0x80;
   int i;
   for(i=7;i>=0;i--)
   	{
	    printf("%d",(c&input)>>i);
       c>>=1;
    	}
   printf("\n");
}
